package org.topdowntdd.sample.appfusemodularstruts.webapp.action.person;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.ObjectUtils;
import org.topdowntdd.sample.appfusemodularstruts.manager.PersonManager;
import org.topdowntdd.sample.appfusemodularstruts.model.Person;

public abstract class BaseAction extends org.appfuse.webapp.action.BaseAction {

	private static final PersonManager PERSON_MANAGER_STUD = new PersonManager(){
		
			Long id = 0L;
		
			List<Person> persons = new ArrayList<Person>();
			
			{
				Person person1 = new Person();
				person1.setFirstName("Franz Allan");
				person1.setLastName("See");
				
				Person person2 = new Person();
				person2.setFirstName("Richard Jayson");
				person2.setLastName("See");
				
				Person person3 = new Person();
				person3.setFirstName("Paule Cyrusse");
				person3.setLastName("See");
				
				save(person1);
				save(person2);
				save(person3);
			}
	
			public boolean exists(Long id) {	
				return false;
			}
	
			public Person get(Long id) {
				Person matchingPerson = null;
				
				Iterator<Person> personIterator = persons.iterator();
				while(personIterator.hasNext() && matchingPerson == null) {
					Person person = personIterator.next();
					if(ObjectUtils.equals(id, person.getId())) {
						matchingPerson = person;
					}
				}
				
				return matchingPerson;
			}
	
			public List<Person> getAll() {
				return persons;
			}
	
			public void remove(Long id) {
				Person personToBeRemoved = get(id);
				persons.remove(personToBeRemoved);
			}
	
			public Person save(Person person) {
				if(person.getId() == null) {
					person.setId(id++);
					persons.add(person);
				} else {
					Person currentPerson = get(person.getId());
					int targetIndex = persons.indexOf(currentPerson);
					persons.remove(targetIndex);
					persons.add(targetIndex, person);
				}
				
				return person;
			}
			
		};
	protected PersonManager personManager = PERSON_MANAGER_STUD;

	public void setPersonManager(PersonManager personManager) {
		this.personManager = personManager;
	}

	@Override
	public abstract String execute();
}